// @ts-ignore
import crypto from 'crypto-js'
import { Base64 } from 'js-base64'

const formatNumber = (n) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}
function formatYMR_cn(dateStr) {
  // 将日期格式化成ios可以识别的格式
  dateStr = dateStr.replace(/-/g, '/')
  let date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1)
  const day = String(date.getDate())
  const formattedDate = `${year}年${month}月${day}日`
  return formattedDate
}

function formatDate_dot(dateStr) {
  // 将日期格式化成ios可以识别的格式
  dateStr = dateStr.replace(/-/g, '/')
  let date = new Date(dateStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('.')
}

function openSettingModal(
  title,
  content,
  confirmText
) {
  wx.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmText: confirmText,
    success() {
      wx.openSetting({
        success(res) {
          console.log('openting authSetting:', res.authSetting)
        },
        fail: (error) => {
          console.log('error:', error)
        }
      })
    }
  })
}

function getAuthSetting(
  scope,
  successCallback,
  failCallback
) {
  console.log('getAuthSetting:', scope)
  wx.getSetting({
    success(res) {
      console.log('res.authSetting:', res.authSetting)
      // alert('getAuthSetting:'+scope+'|||'+ (Object.keys(res.authSetting).join(','))+'|||'+Object.values(res.authSetting).join(','))
      if (res.authSetting[scope]) {
        // 开始录音
        successCallback()
      } else {
        // 没有授权,就授权
        wx.authorize({
          scope: scope,
          success() {
            successCallback()
          },
          fail() {
            failCallback()
          }
        })
      }
    },
    fail(error) {
      console.error('getAuthSetting error:', error)
      // alert('getAuthSetting:'+ JSON.stringify(error))
      failCallback()
    }
  })
}

function isLogin() {
  return !!wx.getStorageSync('token')
}



function randomFileName(ext = '') {
  const randomString =
    Date.now().toString(36) + Math.random().toString(36).substring(2)
  return randomString + ext
}

function formatSeconds(seconds) {
  seconds = Math.floor(seconds)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(
    remainingSeconds
  ).padStart(2, '0')}`
}

function maskPhoneNumber(phoneNumber) {
  if (phoneNumber) {
    return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(7)
  } else {
    return ''
  }
}
function alert(content) {
  wx.showModal({
    title: '',
    content: content,
    showCancel: false
  })
}

function throttle(func, delay) {
  let timer = null 
  return function () {
    if (!timer) {
      func.apply(this, arguments)
      timer = setTimeout(() => {
        timer = null
      }, delay)
    }
  }
}
function randomStr(length = 4) {
  let result = ''
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

function computeSignature(accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(
    crypto.HmacSHA1(canonicalString, accessKeySecret)
  )
}
function getAliSTS(credentials) {
  const date = new Date()
  date.setHours(date.getHours() + 1)
  const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
      // 限制上传大小。
      ['content-length-range', 0, 1024 * 1024 * 1024]
    ]
  }
  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  const signature = computeSignature(credentials.accessKeySecret, policy)
  const formData = {
    OSSAccessKeyId: credentials.accessKeyId,
    signature,
    policy,
    'x-oss-security-token': credentials.securityToken
  }
  return formData
}


function getStatusBarAndMenuButtonInfo() {
  // 单位都是px
  // 胶囊高度
  let menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  let menuButtonHeight = menuButtonInfo.height //  获取胶囊高度
  let winInfo = wx.getWindowInfo()
  // 状态栏高度
  let statusBarHeight = winInfo.statusBarHeight
  // 胶囊距离状态栏边距
  let menuButtonGutter = menuButtonInfo.top - statusBarHeight //  获取top值
  // 导航栏高度：胶囊按钮+上下边距
  let menuBarHeight = menuButtonHeight + menuButtonGutter * 2
  return { menuButtonHeight, statusBarHeight, menuButtonGutter, menuBarHeight }
}



function getAudioUrl(audioUrl) {
  // console.log('getAudioUrl:', audioUrl)
  return new Promise((resolve) => {
    const deviceInfo = wx.getDeviceInfo()
    let isIos = deviceInfo.system.toLowerCase().includes('ios')
    if (isIos) {
      resolve(audioUrl)
    } else {
      // 安卓的话，需要先把文件下载下来才能播放
      wx.downloadFile({
        url: audioUrl,
        success: (res) => {
          // console.log('download res:',res)
          // console.log('that.data._audioContext2:',that.data._audioContext)
          if (res.statusCode === 200) {
            resolve(res.tempFilePath)
          }else {
            resolve(audioUrl)
          }
        },
        fail: (err) => {
          console.log('download err:', err)
          resolve(audioUrl)
        }
      })
    }
  })
}

module.exports = {
  formatTime,
  formatDate_dot,
  openSettingModal,
  getAuthSetting,
  isLogin,
  randomFileName,
  formatSeconds,
  maskPhoneNumber,
  alert,
  formatYMR_cn,
  throttle,
  randomStr,
  getAliSTS,
  getStatusBarAndMenuButtonInfo,
  getAudioUrl
}
